<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of AgencyController
 *
 * @author Poh Nean
 */
class SystemController extends PsController {

	public $defaultAction = 'update';
	public $layout = 'manage';

	public function accessRules() {
		return CMap::mergeArray(array(
					array('allow',
						'actions' => array('update', 'appearance', 'appearanceDefaults', 'numbering', 'headersFooters', 'menu'),
						'roles' => array('ManageAgency.SystemSettings.Manage'),
					),
						), parent::accessRules());
	}
	
	public function actionUpdate() {
		$agency = $this->loadAgency();
		$agency->setScenario('agency_update');

		if (isset($_POST['Agency'])) {
			$agency->attributes = $_POST['Agency'];

			if ($agency->save()) {
				PsSystemMessage::add('Your changes have been saved', 'success');
				$this->refresh();
			}
		}

		$data = array();
		$data['agency'] = $agency;
		$this->render('update', $data);
	}

	public function actionAppearance() {

		$agency = $this->loadAgency();

		if (isset($_POST['Agency'])) {
			$agency->attributes = $_POST['Agency'];
			$upload = CUploadedFile::getInstance($agency, 'logo');

			$agency->saveLogo($upload);

			$this->refresh();
		}

		$data = array();
		$data['agency'] = $agency;
		$this->render('appearance', $data);
	}

	public function actionNumbering($type = 'Transaction') {
		$agency = $this->loadAgency();
		if ($agency->settings == null) {
			$agency->settings = array();
		}

		$documentNumbering = DocumentNumbering::getInstance($type);
		$documentNumberingSettings = $agency->getSetting($type . 'Numbering');
		if (!empty($documentNumberingSettings)) {
			$documentNumbering->attributes = $documentNumberingSettings;
		}
		$documentNumberingClass = get_class($documentNumbering);

		$title = preg_replace('/(?<!\ )[A-Z]/', ' $0', $type);
		
		if (!empty($_POST[$documentNumberingClass])) {
			// do validation
			$documentNumbering->attributes = $_POST[$documentNumberingClass];

			$isValid = $documentNumbering->validate();
			if ($isValid) {
				$agency->setSetting($type . 'Numbering', $documentNumbering->attributes);

				if ($agency->save(true, array('settings'))) {
					PsSystemMessage::add('Your changes have been saved.', 'success');
					$this->refresh();
				}
			}
		}



		$data = array();
		$data['title'] = $title;
		$data['agency'] = $agency;
		$data['type'] = $type;
		$data['documentNumbering'] = $documentNumbering;
		$this->render('numbering', $data);
	}

	public function actionHeadersFooters() {
		$agency = $this->loadAgency();

		if ($agency->settings == null) {
			$agency->settings = array();
		}

		if (!empty($_POST['AgencySetting'])) {
			foreach ($_POST['AgencySetting'] as $key => $value) {
				$agency->setSetting($key, $value);
			}

			if ($agency->save(true, array('settings'))) {
				PsSystemMessage::add('Your changes have been saved.', 'success');
				$this->refresh();
			}
		}

		$data = array();
		$data['agency'] = $agency;
		$this->render('headers_footers', $data);
	}

	public function generateWidgetScript() {
		$agency = $this->loadAgency();

		$js = CHtml::tag('div', array('id' => 'ps-mls-root')) . "\n";
		$js .= CHtml::openTag('script', array('type' => 'text/javascript')) . "\n";
		$js .= <<<JS
	var _psq = _psq || {};
	_psq.app_key = '{$agency->app_key}';

	(function() {
		var ps = document.createElement('script'); ps.type = 'text/javascript'; ps.async = true;
		ps.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + '{$_SERVER['HTTP_HOST']}/js/mls/mls.js';
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ps, s);
	})();

JS;
		$js .= CHtml::closeTag('script');

		return $js;
	}

	/**
	 * @return Agency the agency of the currently logged on user.
	 */
	public function loadAgency() {
//		$selectedAgencyId = Yii::app()->user->getSelectedAgencyId();
//		if ($selectedAgencyId === null) {
//			return Yii::app()->user->model->agency;
//		} else {
//			return Agency::model()->findByAttributes(array(
//				'id' => $selectedAgencyId,
//				'parent_id' => Yii::app()->user->model->agency_id,
//			));
//		}	
		
		return Yii::app()->user->getSelectedAgency();
	}

	public function actionMenu() {
		$agency = $this->loadAgency();
		$agencySettings = array();

		if ($agency->settings != null) {
			$agencySettings = $agency->settings;
		}
		$defaultSettings = $agency->defaultSettings;

		if (!empty($_POST['AgencySetting'])) {
			$newAgencySettings = $_POST['AgencySetting'];

			unset($agencySettings['Menu']);

			// set empty values to default values
			foreach ($newAgencySettings['Menu'] as $app => $appMenuSettings) {
				foreach ($appMenuSettings as $key => $value) {
					if (empty($value)) {
						$value = $defaultSettings['Menu'][$app][$key];
					}
					$newAgencySettings['Menu'][$app][$key] = $value;
				}
			}

			$agency->settings = CMap::mergeArray($agencySettings, $newAgencySettings);

			if ($agency->save(true, array('settings'))) {
				PsSystemMessage::add('Your changes have been saved.', 'success');
				$this->refresh();
			}
		}


		$topachieverMenuSettings = array();
		foreach ($defaultSettings['Menu']['TopAchiever'] as $key => $value) {
			$menuName = str_replace('.', ' > ', $key);
			$menuName = trim(preg_replace('/((?:^|[A-Z])[a-z]+)/', " $1", $menuName)); // camelcase to space

			$topachieverMenuSettings[] = array(
				'id' => $key,
				'name' => $menuName,
				'value' => $agencySettings['Menu']['TopAchiever'][$key]
			);
		}

		$prestigeMenuSettings = array();
		foreach ($defaultSettings['Menu']['Prestige'] as $key => $value) {
			$menuName = str_replace('.', ' > ', $key);
			$menuName = trim(preg_replace('/((?:^|[A-Z])[a-z]+)/', " $1", $menuName)); // camelcase to space

			$prestigeMenuSettings[] = array(
				'id' => $key,
				'name' => $menuName,
				'value' => $agencySettings['Menu']['Prestige'][$key]
			);
		}

		$topachieverMenuDataProvider = new CArrayDataProvider($topachieverMenuSettings, array(
			'pagination' => array(
				'pagesize' => 1000
			)
		));
		$prestigeMenuDataProvider = new CArrayDataProvider($prestigeMenuSettings, array(
			'pagination' => array(
				'pagesize' => 1000
			)
		));

		$data = array();
		$data['topachieverMenuDataProvider'] = $topachieverMenuDataProvider;
		$data['prestigeMenuDataProvider'] = $prestigeMenuDataProvider;
		$data['agency'] = $agency;
		$data['agencySettings'] = $agencySettings;
		$this->render('menu', $data);
	}

	public function actionAppearanceDefaults() {
		$agency = $this->loadAgency();

		if ($agency->settings == null) {
			$agency->settings = array();
		}

		if (!empty($_POST['AgencySetting'])) {
			foreach ($_POST['AgencySetting'] as $key => $value) {
				$agency->setSetting($key, $value);
			}

			if ($agency->save(true, array('settings'))) {
				PsSystemMessage::add('Your changes have been saved.', 'success');
				$this->refresh();
			}
		}

		$data = array();
		$data['agency'] = $agency;

		$this->render('appearance_defaults', $data);
	}

}

?>
